﻿using BaoVeBienCuong.Playgame.army;
using BaoVeBienCuong.Store;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using NapThe;
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Navigation;

namespace BaoVeBienCuong.SelectMap
{
    public partial class SelectMapAndStore : PhoneApplicationPage
    {
        string trangthai; // giữa selectmap và store
        public static ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        public static Vector2 sizeMap, DoLech;
        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
        public static long vang = 300000, sao;
        int savebutton; // luu trang thai dang chon de xu ly giao dien ky nang
        Vector2 start, curtouch;
        Texture2D BoundMap, BoundShop, ButtonShop, Vang, Sao;
        public Texture2D imageNgoai;
        public static Thanh[] thanh = new Thanh[12];
        SpriteFont font;
        Selection selection;
        public static NapXu napxu;
        bool isSelectShop;
        bool isNangCapKyNang;
        int temp = -1;
        int second;
        public static int levelselected = 0;
        public static int capdoselected = 1;
        ButtonStore[] button = new ButtonStore[6];//danh mục
        KyNang[] buttonKyNang = new KyNang[16]; // nâng cấp kĩ năng
        NoiDungNangCap NoiDungNangCap = new NoiDungNangCap();
        TuongButton[] tuongbuttons = new TuongButton[8];
        SaveKyNang SaveKyNang = new SaveKyNang(); // lưu file
        public List<LinhCanChien> linhdemos;
        public static bool isClickVang;
        private int choiceLinh, choiceLevel = 1;
        UIElementRenderer elementRenderer;
        public SelectMapAndStore()
        {
            InitializeComponent();
            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;
            // Create a timer for this page
            napxu = new NapXu(LayoutRoot);
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
        }
        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (GamePage.contentManager != null)
            {
                GamePage.contentManager.Unload();
                GamePage.setDiem = false;
            }
            MainPage.contentManager.Unload();

            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);
            // TODO: use this.content to load your game content here
            GamePage.scale = 0.8f;
            GamePage.DoLech = new Vector2(0, 0);
            linhdemos = new List<LinhCanChien>();
            AddLinh();
            foreach (LinhCanChien linh in linhdemos)
            {
                linh.Load(contentManager);
            }
            font = contentManager.Load<SpriteFont>("fonts/font");
            isSelectShop = false;
            selection = new Selection();
            selection.Load(contentManager);
            for (int i = 0; i < 12; i++)
            {
                thanh[i] = new Thanh();
                thanh[i].setIndex(i);
                thanh[i].Load(contentManager);
            }
            FileThanh.getData(ref thanh);
            sao = FileThanh.getSao();
            for (int i = 0; i < 6; i++)
            {
                button[i] = new ButtonStore(i);
                button[i].Load(contentManager);
            }
            buttonKyNang = SaveKyNang.readSaveKyNang();
            for (int i = 0; i < 16; i++)
            {
                buttonKyNang[i].Load(contentManager);
                buttonKyNang[i].setGia(i);
            }
            NoiDungNangCap = new NoiDungNangCap();
            for (int i = 0; i < 8; i++)
            {
                tuongbuttons[i] = new TuongButton(i);
                tuongbuttons[i].Load(contentManager);
            }

            BoundMap = contentManager.Load<Texture2D>("images/selectMap/map");
            BoundShop = contentManager.Load<Texture2D>("images/store/downBackground");
            Vang = contentManager.Load<Texture2D>("images/store/gold");
            Sao = contentManager.Load<Texture2D>("images/store/star");
            ButtonShop = contentManager.Load<Texture2D>("images/selectMap/mapScreenButton");
            imageNgoai = contentManager.Load<Texture2D>("images/store/skillType");
            trangthai = "selectmap";
            sizeMap = new Vector2(1280, 720);
            DoLech = new Vector2(0, 0);
            GamePage.trangthaigame = 0;
            GamePage.isPause = false;
            // Start the timer
            timer.Start();
            vang = NapTheDienThoaiController.numberOfMoney(storage);
            //uiElementRenderer = new UIElementRenderer(LayoutRoot,
            // SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width,
            // SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height);
            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            SaveKyNang.write_KyNang(buttonKyNang);
            timer.Stop();
            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            //selectmap
            #region
            if (trangthai.Equals("selectmap"))
            {
                TouchCollection touchs = TouchPanel.GetState();
                foreach (TouchLocation touch in touchs)
                {
                    if (touch.State == TouchLocationState.Pressed)
                    {
                        start = touch.Position;
                        curtouch = touch.Position;
                    }
                    if (touch.State == TouchLocationState.Moved)
                    {
                        if (!selection.getVisible())
                        {
                            DoLech += touch.Position - curtouch;
                            curtouch = touch.Position;
                            if (DoLech.X > 0) DoLech.X = 0;
                            if (DoLech.Y > 0) DoLech.Y = 0;
                            if (-DoLech.X + 800 > sizeMap.X) DoLech.X = 800 - sizeMap.X;
                            if (-DoLech.Y + 480 > sizeMap.Y) DoLech.Y = 480 - sizeMap.Y;
                            istouchButtonShop(curtouch);
                        }
                        else
                        {
                            curtouch = touch.Position;
                            selection.isSelectBando(curtouch);
                            selection.isSelectChoi(curtouch);
                        }
                    }
                    if (touch.State == TouchLocationState.Released)
                    {

                        if (!selection.getVisible())
                        {
                            if (istouchButtonShop(curtouch))
                            {
                                if (Vector2.Distance(curtouch, start) < 50)
                                {
                                    isSelectShop = false;
                                    trangthai = "phattrien";
                                    MainPage.PlayHieuUng("Click", false);

                                    GamePage.DoLech = new Vector2(0, 0);
                                }
                                else
                                {
                                    isSelectShop = false;
                                }
                            }
                            else
                            {
                                for (int i = 0; i < 12; i++)
                                {
                                    if (Vector2.Distance(curtouch, start) < 50)
                                    {
                                        if (thanh[i].isSelect(curtouch - DoLech))
                                        {
                                            MainPage.PlayHieuUng("Click", false);
                                            if (thanh[i].isOpen()) levelselected = i;
                                            selection.set(thanh[i]);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            selection.isChangeMode(curtouch);
                            if (selection.isSelectBando(curtouch))
                            {
                                selection.setVisible(false);
                                thanh[levelselected].setIsSelected(false);
                            }
                            if (selection.isSelectChoi(curtouch))
                            {
                                MainPage.StopNhac("MapSelect");
                                selection.setVisible(false);
                                thanh[levelselected].setIsSelected(false);
                                NavigationService.Navigate(new Uri("/../GamePage.xaml", UriKind.Relative));
                            }
                        }
                    }
                }
            }
            #endregion

            // shop
            else
            {
                if (!napxu.isVisible())
                {
                    foreach (TuongButton tuongbutton in tuongbuttons)
                    {
                        if (tuongbutton.getType() == (-(int)GamePage.DoLech.X / 400))
                        {
                            tuongbutton.setTouch(true);
                        }
                        else tuongbutton.setTouch(false);
                    }
                    TouchCollection touchs = TouchPanel.GetState();
                    foreach (TouchLocation touch in touchs)
                    {
                        //sự kiện chạm và vuốt
                        #region
                        if (touch.State == TouchLocationState.Pressed)
                        {
                            start = touch.Position;
                            curtouch = touch.Position;
                        }
                        if (touch.State == TouchLocationState.Moved)
                        {
                            if (trangthai.Equals("tuong") && start.Y >= 100 && start.X <= 550 && start.Y <= 450)
                            {
                                GamePage.DoLech.X += touch.Position.X - curtouch.X;
                                curtouch = touch.Position;
                                if (GamePage.DoLech.X > 0) GamePage.DoLech.X = 0;
                                if (-GamePage.DoLech.X + 800 > 2000) GamePage.DoLech.X = 800 - 2000;
                            }
                            else
                            {
                                curtouch = touch.Position;
                                for (int i = 0; i < 6; i++)
                                {
                                    button[i].isTouch(curtouch);
                                }
                                foreach (TuongButton tuongbutton in tuongbuttons)
                                {
                                    tuongbutton.isTouch(curtouch);
                                }
                            }
                        }
                        #endregion

                        //sự kiện chính
                        if (touch.State == TouchLocationState.Released)
                        {
                            //xử lí các nút bấm
                            #region
                            curtouch = touch.Position;
                            if (button[5].isTouch(curtouch)) // nút thoát
                            {
                                savebutton = 5;
                                trangthai = "selectmap";
                                button[0].setTouch(true);
                                button[5].setTouch(false);
                                SaveKyNang.write_KyNang(buttonKyNang);
                            }
                            else if (button[3].isTouch(curtouch)) // nút kỹ năng
                            {
                                savebutton = 3;
                                trangthai = "kynang";
                                button[0].setTouch(false);
                                button[1].setTouch(false);
                                button[2].setTouch(false);
                                button[4].setTouch(false);
                            }
                            else if (button[0].isTouch(curtouch) || button[1].isTouch(curtouch))//2 nút đầu chưa được phát triển
                            {
                                savebutton = 0;
                                trangthai = "phattrien";
                                if (button[0].isTouch(curtouch)) button[1].setTouch(false);
                                else button[0].setTouch(false);
                                button[3].setTouch(false);
                                button[2].setTouch(false);
                                button[4].setTouch(false);
                            }
                            else if (button[2].isTouch(curtouch)) // nút mua tướng
                            {
                                savebutton = 2;
                                trangthai = "tuong";
                                button[0].setTouch(false);
                                button[3].setTouch(false);
                                button[1].setTouch(false);
                                button[4].setTouch(false);
                            }
                            else if (button[4].isTouch(curtouch))
                            {
                                napxu.NapXuSms();
                                isClickVang = true;
                                button[0].setTouch(false);
                                button[3].setTouch(false);
                                button[1].setTouch(false);
                                button[2].setTouch(false);
                            }
                            #endregion

                            //xử lí tại giao diện kỹ năng
                            #region
                            if (trangthai.Equals("kynang"))
                            {
                                for (int i = 0; i < 16; i++)
                                {
                                    buttonKyNang[i].isTouch(touch.Position);
                                    if (buttonKyNang[i].isSelect)
                                    {
                                        temp = i;
                                        NoiDungNangCap.setNoiDung(temp);
                                    }
                                    if (istouchbtKyNang(touch.Position) && temp != -1)
                                    {
                                        buttonKyNang[temp].isSelect = true;
                                        if (!buttonKyNang[temp].isNangCap)
                                        {
                                            if (temp % 4 == 0)
                                            {
                                                if (!napxu.CheckMoney((int)buttonKyNang[temp].getVang()) && vang >= buttonKyNang[temp].getVang() && sao >= buttonKyNang[temp].getSao())
                                                {
                                                    vang -= buttonKyNang[temp].getVang();
                                                    napxu.SubMoney((int)buttonKyNang[temp].getVang());
                                                    sao -= buttonKyNang[temp].getSao();
                                                    FileThanh.saveSao((int)sao);
                                                    buttonKyNang[temp].isNangCap = true;
                                                    MainPage.PlayHieuUng("Upgrade", false);


                                                }

                                            }
                                            else
                                                if (buttonKyNang[temp - 1].isNangCap)
                                                {
                                                    if (!napxu.CheckMoney((int)buttonKyNang[temp].getVang()) && vang >= buttonKyNang[temp].getVang() && sao >= buttonKyNang[temp].getSao())
                                                    {
                                                        vang -= buttonKyNang[temp].getVang();
                                                        napxu.SubMoney((int)buttonKyNang[temp].getVang());
                                                        sao -= buttonKyNang[temp].getSao();
                                                        FileThanh.saveSao((int)sao);
                                                        buttonKyNang[temp].isNangCap = true;
                                                        MainPage.PlayHieuUng("Upgrade", false);


                                                    }
                                                }
                                        }
                                    }
                                }
                            }

                            #endregion

                            //xử lí tại giao diện mua tướng
                            else if (trangthai.Equals("tuong"))
                            {
                                GamePage.DoLech.X = (((int)GamePage.DoLech.X - 200) / 400) * 400;
                                if (curtouch.X < 450 && curtouch.Y < 450) // phạm vi chọn tướng
                                {
                                    for (int i = 0; i < linhdemos.Count; i++)
                                    {
                                        linhdemos[i].setNangCap(false);
                                    }
                                    for (int i = 0; i < linhdemos.Count; i++)
                                    {
                                        linhdemos[i].setNangCap(false);
                                        if (linhdemos[i].isTouched(curtouch, false))
                                        {
                                            choiceLinh = i;
                                            linhdemos[i].setNangCap(true);
                                            break;
                                        }
                                    }
                                }
                                else // phạm vi chọn button
                                {
                                    foreach (TuongButton tuongbutton in tuongbuttons)
                                    {
                                        if (tuongbutton.isTouch(curtouch))
                                        {
                                            if (tuongbutton.getType() < 4)
                                            {
                                                GamePage.DoLech.X = tuongbutton.getType() * -400;
                                            }
                                            else if (tuongbutton.getType() < 7)
                                            {
                                                choiceLevel = tuongbutton.getType() - 3;
                                            }
                                            else
                                            {
                                                if (linhdemos[choiceLinh].getLock())
                                                {
                                                    if (!napxu.CheckMoney((int)linhdemos[choiceLinh].getInfo(choiceLinh, choiceLevel).getGia()) && vang >= linhdemos[choiceLinh].getInfo(choiceLinh, choiceLevel).getGia())
                                                    {
                                                        MainPage.PlayHieuUng("Upgrade", false);
                                                        vang -= (long)linhdemos[choiceLinh].getInfo(choiceLinh, choiceLevel).getGia();
                                                        napxu.SubMoney((int)linhdemos[choiceLinh].getInfo(choiceLinh, choiceLevel).getGia());
                                                        FileTuong.SaveFile(ref linhdemos, choiceLinh);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);
            elementRenderer.Render();
            // TODO: Add your drawing code here
            spriteBatch.Begin();
            if (trangthai.Equals("selectmap"))
            {
                #region
                spriteBatch.Draw(BoundMap, DoLech, new Rectangle(0, 0, 640, 360), Color.White, 0, Vector2.Zero, 2.0f, SpriteEffects.None, 0);
                for (int i = 0; i < 12; i++)
                {
                    thanh[i].Draw(spriteBatch, font);
                }
                if (selection.getVisible())
                {
                    selection.Draw(spriteBatch, font);
                }
                else
                {
                    if (!isSelectShop)
                    {
                        spriteBatch.Draw(ButtonShop, new Vector2(549, 410), new Rectangle(0, 210, 251, 70), Color.White);
                    }
                    else
                    {

                        spriteBatch.Draw(ButtonShop, new Vector2(549, 410), new Rectangle(251, 210, 251, 70), Color.White);
                    }
                }
                #endregion
            }
            else
            {
                #region
                spriteBatch.Draw(BoundShop, new Vector2(-28, 0), new Rectangle(0, 0, 640, 360),
                                               Color.White, 0, Vector2.Zero, 4 / 3.0f, SpriteEffects.None, 0);
                if (isClickVang && !napxu.isVisible())
                {
                    vang = NapTheDienThoaiController.numberOfMoney(storage);

                    button[savebutton].setTouch(true);
                    button[4].setTouch(false);
                    isClickVang = false;
                }
                spriteBatch.Draw(Vang, new Vector2(480, 25), new Rectangle(0, 0, 79, 47),
                                                Color.White, 0, Vector2.Zero, 0.7f, SpriteEffects.None, 0);
                spriteBatch.DrawString(font, vang.ToString(), new Vector2(540, 20), Color.White);
                spriteBatch.Draw(Sao, new Vector2(625, 15), new Rectangle(0, 0, 61, 58),
                                                Color.White, 0, Vector2.Zero, 0.7f, SpriteEffects.None, 0);
                spriteBatch.DrawString(font, sao.ToString(), new Vector2(670, 20), Color.White);
                for (int i = 0; i < 6; i++)
                {
                    button[i].Draw(spriteBatch);
                }
                #endregion
                if (trangthai.Equals("phattrien"))
                {
                    spriteBatch.DrawString(font, "Chức năng đang được phát triển", new Vector2(250, 250), Color.White);
                }
                else if (trangthai.Equals("kynang"))
                {
                    #region
                    for (int i = 0; i < 16; i++)
                    {
                        buttonKyNang[i].Draw(spriteBatch);
                    }
                    for (int i = 0; i < 4; i++)
                    {
                        Vector2 position = new Vector2(10, 140);
                        spriteBatch.Draw(imageNgoai, new Vector2(position.X, (position.Y + i * 140) * 0.7f), new Rectangle(i * 108, 0, 108, 108), Color.White, 0, Vector2.Zero, 0.7f, SpriteEffects.None, 0);
                    }
                    if (!isNangCapKyNang)
                    {
                        spriteBatch.Draw(ButtonShop, new Vector2(549, 410), new Rectangle(0, 210, 251, 70), Color.White, 0.0f, Vector2.Zero, 0.7f, SpriteEffects.None, 1.0f);
                    }
                    else
                    {
                        spriteBatch.Draw(ButtonShop, new Vector2(549, 410), new Rectangle(251, 210, 251, 70), Color.White, 0.0f, Vector2.Zero, 0.7f, SpriteEffects.None, 1.0f);
                        second++;
                        if (second == 10)
                        {
                            isNangCapKyNang = false;
                            second = 0;
                        }
                        // spriteBatch.Draw(ButtonShop, new Vector2(549, 410), new Rectangle(251, 210, 251, 70), Color.White, 0.0f, Vector2.Zero, 0.7f, SpriteEffects.None, 1.0f);
                    }

                    NoiDungNangCap.Draw(spriteBatch, font);
                    #endregion
                }
                else if (trangthai.Equals("tuong"))
                {
                    foreach (LinhCanChien linh in linhdemos)
                    {
                        linh.Draw(spriteBatch, font, false);
                    }
                    spriteBatch.Draw(BoundShop, new Vector2(422, 100), new Rectangle(450 * 3 / 4, 100 * 3 / 4, 1000, 600), Color.White, 0, Vector2.Zero, 4 / 3.0f, SpriteEffects.None, 0);
                    foreach (TuongButton tuongbutton in tuongbuttons)
                    {
                        tuongbutton.Draw(spriteBatch);
                    }
                    foreach (LinhCanChien linh in linhdemos)
                    {
                        if (linh.getNangCap()) linh.DrawInformation(spriteBatch, font, choiceLinh, choiceLevel);
                    }
                }
                // uiElementRenderer.Render();
                spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            }
            spriteBatch.End();

        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (trangthai.Equals("selectmap"))
            {
                if (selection.getVisible())
                {
                    selection.setVisible(false);
                    thanh[levelselected].setIsSelected(false);
                    e.Cancel = true;
                }
                else
                {
                    base.OnBackKeyPress(e);
                }

            }
            else
            {
                if (napxu.isVisible())
                {
                    napxu.Collapsed();
                    e.Cancel = true;
                }
                else
                {
                    SaveKyNang.write_KyNang(buttonKyNang);
                    trangthai = "selectmap";
                    for (int i = 0; i < 6; i++)
                    {
                        button[i].setTouch(i == 0 ? true : false);
                    }
                    e.Cancel = true;
                }
            }
        }
        public bool istouchButtonShop(Vector2 touch)
        {
            isSelectShop = false;
            if (touch.X >= 549 && touch.Y >= 410)
            {
                isSelectShop = true;
                return true;
            }
            return false;
        }

        public bool istouchbtKyNang(Vector2 touch)
        {

            if (touch.X >= 549 && touch.X < 650 && touch.Y >= 410)
            {
                isNangCapKyNang = true;
                MainPage.PlayHieuUng("Click", false);

                return true;
            }
            return false;
        }
        public void AddLinh()
        {
            LinhCanChien lcc;
            LinhTamXa ltx;
            for (int i = 0; i < 12; i++)
            {
                if (i / 3 == 0 || i / 3 == 2)
                {
                    lcc = new LinhCanChien((i / 3 == 0 ? "sword" : "knight"), i % 3);
                    lcc.setPosition(new Vector2(i % 3 == 0 ? (200 + 520 * (i / 3)) : (50 + 510 * (i / 3) + 300 * ((i - 1) % 3)), i % 3 == 0 ? 200 : 400));
                    linhdemos.Add(lcc);
                }
                else
                {
                    ltx = new LinhTamXa((i / 3 == 1 ? "archer" : "shaman"), i % 3);
                    ltx.setPosition(new Vector2(i % 3 == 0 ? (200 + 520 * (i / 3)) : (50 + 510 * (i / 3) + 300 * ((i - 1) % 3)), i % 3 == 0 ? 200 : 400));
                    linhdemos.Add(ltx);
                }
            }
            FileTuong.getData(ref linhdemos);
        }
    }
}